<template>
  <div class="red-container">
    <div class="privateRed" v-if="privateRed.length > 0">
      <span>{{privateRed.length}}</span>
      <div @click="grabPrivateRed()"></div>
    </div>
    <el-dialog :visible.sync="sendVisible" :lock-scroll="false" :modal-append-to-body="false" :modal="true"
               customClass="send-red-dialog reset-dialog" @close="closeSend()">
      <div class="send-red">
        <h3>{{send.name ? '给' + send.name + '发红包' : '发送群红包'}}</h3>
        <div class="send-red-group"><input type="text" v-model="send.price"
                                           :placeholder="'总熙币数(您共有'+$parent.user.money+'熙币)'">
          <p>熙币</p></div>
        <div class="send-red-group"><input type="text" :readonly="sendType === 1 || sendType === 3" v-model="send.num"
                                           placeholder="请输入红包个数">
          <p>个</p></div>
        <div class="send-radios" v-if="sendType < 3">
          <p @click="sendType = 0" :class="{on: sendType === 0}" style="float: left;">发给所有人</p>
          <p @click="sendType = 1" :class="{on: sendType === 1}" style="float: right;">仅发给老师</p>
        </div>
      </div>
      <button type="button" class="send-btn" @click="sendRed()">确认发送</button>
    </el-dialog>
    <el-dialog :visible.sync="grabVisible" :lock-scroll="false" :modal-append-to-body="false" :modal="true"
               customClass="grab-red-dialog reset-dialog" @close="closeSend()">
      <div class="grab-con">
        <h3>{{redInfo.isPrivate ? `收到了${redInfo.list.length}个红包` : `土豪:${redInfo.name}`}}</h3>
        <div class="grab-money">{{redInfo.data || 0}}熙币</div>
        <p class="grab-gray" v-if="redInfo.status ==='zero'">手慢了，红包已派完</p>
        <p class="grab-blue" v-else>已存入钱包，可用于发红包</p>
        <ul class="grab-list">
          <li v-for="red in redInfo.list"><p>{{`${red.name}${redInfo.isPrivate ? '发来' : '抢到'}`}}</p> <span>{{red.money}}熙币</span>
          </li>
        </ul>
        <p class="grab-num" v-if="!redInfo.isPrivate"> {{`已领取 ${redInfo.already} / ${redInfo.all}`}} </p>
      </div>
    </el-dialog>
    <template v-if="showClocker">
      <div class="red-clocker-up" v-if="timeUp" @click="grabTimeRed(timeRedId, timeRedBatch)"></div>
      <div class="red-clocker" v-else>
        <span>{{hours}}</span>:<span>{{minute}}</span>:<span>{{second}}</span>
      </div>
    </template>
  </div>
</template>
<script>
  export default {
    created () {
      this.$once('first', (data) => {
        console.log('first time red', data)
        this.getTimeRedCallBack(data)
      })
    },
    props: {
      privateRed: Array
    },
    data () {
      return {
        redInfo: {},
        sendType: 0,
        sendVisible: false,
        send: {
          price: '',
          num: '',
          name: '',
          id: ''
        },
        grabVisible: false,
        hours: '00',
        minute: '00',
        second: '00',
        count: null,
        interval: null,
        timeout: null,
        showClocker: false,
        timeUp: false,
        timeRedId: null,
        timeRedBatch: null
      }
    },
    methods: {
      calcTime () {
        let hours = parseInt(this.count / (60 * 60))
        this.hours = (hours < 10 ? '0' : '') + hours

        let n = this.count % (60 * 60)
        let minute = parseInt(n / 60)
        this.minute = (minute < 10 ? '0' : '') + minute

        let second = parseInt(n % 60)
        this.second = (second < 10 ? '0' : '') + second
        console.log(this.count)
      },
      getTimeRed () {
        this.timeUp = false
        clearTimeout(this.timeout)
        clearInterval(this.interval)
        this.$http.post('/index/beta_api/getNextTimeingRedbag')
          .then(data => {
            this.getTimeRedCallBack(data)
          })
      },
      getTimeRedCallBack (data) {
        let {now_type, time_diff, id, batch} = data
        this.timeRedBatch = batch
        this.timeRedId = id
        switch (now_type) {
          case 'none':
            this.showClocker = false
            break
          case 'ing':
            this.timeUp = true
          case 'wait':
            this.showClocker = true
            this.count = time_diff
            this.start()
        }
      },
      start () {
        this.calcTime()
        this.interval = setInterval(() => {
          this.count -= 1
          if (this.count <= 0) {
            clearInterval(this.interval)
            this.second = '00'
            this.timeUp = !this.timeUp
            if (this.timeUp) { // 红包倒计时结束操作
              this.timeout = setTimeout(() => {
                console.log('end Time')
                this.getTimeRed()
              }, 1000 * 60 * 2)
            } else {  // 抢包倒计时结束操作
              this.getTimeRed()
            }
          }
          this.calcTime()
        }, 1000)
      },
      closeSend () {
        this.sendType = 0
        this.send = {
          price: '',
          num: ''
        }
      },
      showSend (user) {
        if (user) {
          this.send.name = user.name
          this.send.id = user.userid || user.uid
          this.sendType = 3
        }
        this.sendVisible = true
      },
      sendRed () {
        let {price, num, id} = this.send

        if (price < 0.1 || isNaN(price)) {
          this.$message.error('最少发送0.1个熙币!')
          return
        }
        if (!/^\+?[1-9][0-9]*$/.test(num)) {
          this.$message.error('请输入正确的红包个数!')
          return
        }
        this.$http.post(id ? '/index/beta_api/sendPrivateRedbag' : '/index/beta_api/sendRedbag', {
          to: id,
          price,
          num,
          type: this.sendType
        }).then(data => {
          this.$parent.updateMoney(data.money)
          this.sendVisible = false
        })
      },
      grabTimeRed (id, batch) {
        this.$http.post('/index/beta_api/grabTimingRedbag', {id, batch}).then(data => {
          this.grabCallback(data)
          this.getTimeRed()
        })
      },
      grabPrivateRed (chat) {
        let key = chat ? chat.red_key : ''
        this.$http.post('/index/beta_api/getPrivateRedbag', {key}).then(data => {
          data.isPrivate = true
          this.$parent.privateRed.splice(0, data.list.length)
          this.grabCallback(data, chat)
        })
      },
      grabRed (chat) {
//        let isGrabAll = typeof chat === 'undefined'
//        let key = isGrabAll ? '' : chat.red_key
//        let isPrivate = isGrabAll || chat.type !== 'sendbag'

//        this.$http.post(`/index/beta_api/${isPrivate ? 'getPrivateRedbag' : 'grabRedbag'}`, {key})
//          .then(data => {
//            isGrabAll || (chat.content = 1)
//            this.redInfo = data
//            this.redInfo.isPrivate = isPrivate
//            isPrivate && (this.$parent.privateRed.splice(0, data.list.length))
//            this.$nextTick(() => {
//              this.grabVisible = true
//            })
//          })
        if (chat.type === 'sendprivatbag') {
          this.grabPrivateRed(chat)
          return
        }
        this.$http.post('/index/beta_api/grabRedbag', {key: chat.red_key}).then(data => {
          this.grabCallback(data, chat)
        })

      },
      grabCallback (data, chat) {
        this.$parent.updateMoney(data.money)
        this.redInfo = data
        if (chat) {
          chat.grab = 'true'
        }
        this.$nextTick(() => {
          this.grabVisible = true
        })
      }
    },
    watch: {
      sendType (val) {
        this.send.num = ~[1, 3].indexOf(val) ? 1 : ''
      }
    }
  }
</script>
<style lang="scss">
  @import "style";
</style>
